<template>
  <div class="course-reviews-container">
    <el-container>
      <el-header class="reviews-header">
        <el-page-header @back="$router.go(-1)"></el-page-header>
      </el-header>
      <el-main class="reviews-main" style="width: 1000px;"> 
        <div class="review-summary">
          <h3>总体评价：<el-rate v-model="overallRating" disabled show-score text-color="#ff9900"></el-rate></h3>
          <p>共有 {{ totalReviews }} 条评价</p>
        </div>

        <el-divider></el-divider>

        <div class="review-filters">
          <span>筛选：</span>
          <el-radio-group v-model="filterRating" size="small" @change="fetchReviews">
            <el-radio-button :label="0">全部</el-radio-button>
            <el-radio-button :label="5">五星</el-radio-button>
            <el-radio-button :label="4">四星</el-radio-button>
            <el-radio-button :label="3">三星</el-radio-button>
            <el-radio-button :label="2">二星</el-radio-button>
            <el-radio-button :label="1">一星</el-radio-button>
          </el-radio-group>
        </div>

        <el-timeline v-if="reviews.length > 0">
          <el-timeline-item v-for="review in reviews" :key="review.id" :timestamp="formatTime(review.commentTime)" placement="top">
            <el-card class="review-item-card">
              <div class="review-header-info">
                <el-avatar :src="review.userAvatar ? (review.userAvatar.startsWith('http') ? review.userAvatar : baseUrl + review.userAvatar) : (baseUrl + 'static/img/default-avatar.png')" size="small"></el-avatar>
                <span class="username">{{ review.name || '匿名用户' }}</span>
                <el-rate v-model="review.rating" disabled size="small"></el-rate>
              </div>
              <p class="review-content">{{ review.content }}</p>
              <div v-if="review.image" class="comment-image-wrapper">
                <el-image 
                  style="width: 100px; height: 100px; border-radius: 4px;" 
                  :src="review.image.startsWith('http') ? review.image : baseUrl + review.image"
                  :preview-src-list="[review.image.startsWith('http') ? review.image : baseUrl + review.image]">
                </el-image>
              </div>
              
              <div v-if="review.teacherReply" class="teacher-reply">
                <p>教师回复：{{ review.teacherReply }}</p>
              </div>
              <div class="review-actions">
                <el-button
                  v-if="!review.teacherReply && isTeacher"
                  type="text"
                  size="small"
                  @click="openReplyDialog(review)"
                >回复</el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无评价"></el-empty>

        <div class="pagination-container" v-if="totalReviews > pageSize">
          <el-pagination
            @current-change="handlePageChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="totalReviews"
          ></el-pagination>
        </div>
      </el-main>
    </el-container>

    <el-dialog
      :visible.sync="replyDialogVisible"
      title="回复评价"
      width="500px"
    >
      <el-input
        type="textarea"
        :rows="4"
        placeholder="请输入你的回复"
        v-model="currentReplyContent"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReply">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CourseReviews',
  data() {
    return {
      courseId: this.$route.query.id, 
      overallRating: 0, 
      totalReviews: 0, 
      reviews: [],

      filterRating: 0, // 评价星级筛选，0为全部
      currentPage: 1,
      pageSize: 10, 

      replyDialogVisible: false,
      currentReviewToReply: null,
      currentReplyContent: '',
      isTeacher: false, 
    };
  },
  methods: {

    formatTime(time) {
      if (!time) return ''; 
      const date = typeof time === 'object' && time instanceof Date ? time : new Date(time);
      if (isNaN(date.getTime())) {
          console.warn("Invalid date for formatTime:", time);
          return '无效时间';
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    async fetchReviews() {
      try {
        const { data } = await this.$http.get('comment/page', {
          params: {
            page: this.currentPage,
            limit: this.pageSize,
            courseId: this.courseId,
            rating: this.filterRating,
          }
        });
        if (data && data.code === 0) {
          this.reviews = data.data.list;
          this.totalReviews = data.data.total;
          if (this.totalReviews > 0) {
            const sumRating = this.reviews.reduce((sum, review) => sum + review.rating, 0);
            if(this.filterRating===0){
                this.overallRating = parseFloat((sumRating / this.totalReviews).toFixed(1)); // 保留一位小数
            }
            
          } else {
            if(this.filterRating===0){
                this.overallRating = 0;
            }
          }
          
          this.checkUserRole();

        } else {
          this.$message.error(data.msg || '获取评价列表失败。');
        }
      } catch (error) {
        this.$message.error('获取评价列表失败，请检查网络或后端服务。');
        console.error('Fetch reviews error:', error);
      }
    },

    checkUserRole() {
        const userType = localStorage.getItem('userType');
        this.isTeacher = userType === 'teacher' || userType === 'admin';
    },

    handlePageChange(page) {
      this.currentPage = page;
      this.fetchReviews();
    },
    openReplyDialog(review) {
      this.currentReviewToReply = review;
      this.currentReplyContent = review.teacherReply || ''; // 如果已有回复，则填充
      this.replyDialogVisible = true;
    },
    async submitReply() {
      if (!this.currentReplyContent.trim()) {
        this.$message.warning('回复内容不能为空！');
        return;
      }
      try {
        const { data } = await this.$http.put('/comment/reply', {
          id: this.currentReviewToReply.id,
          teacherReply: this.currentReplyContent,
        });

        if (data && data.code === 0) {
          this.$message.success('回复成功！');
          this.replyDialogVisible = false;
          this.fetchReviews(); // 刷新评论列表，获取最新回复
        } else {
          this.$message.error(data.msg || '回复失败，请稍后再试。');
        }
      } catch (error) {
        this.$message.error('回复失败，请稍后再试。');
        console.error('Submit reply error:', error);
      }
    },
  },
  mounted() {
    // mounted 时立即触发路由参数的监听，从而调用 fetchReviews
  },
  watch: {
    // 监听路由参数变化，确保 courseId 更新后重新加载评论
    '$route.query.id': {
      handler(newId) {
        this.courseId = newId;
        this.currentPage = 1; // 切换课程时重置页码
        this.filterRating = 0; // 切换课程时重置筛选
        this.fetchReviews();
      },
      immediate: true, // 立即执行一次，组件挂载时也加载数据
    },
  },
};
</script>

<style scoped>
.course-reviews-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}
.reviews-header {
  background-color: #fff;
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}
.reviews-main {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}
.review-summary {
  text-align: center;
  margin-bottom: 20px;
}
.review-summary h3 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
  display: flex;
  justify-content: center;
  align-items: center;
}
.review-summary p {
  color: #606266;
}
.review-filters {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px; /* CSS Gap 属性在旧浏览器中可能不兼容，如果需要可以改为 margin-right */
}
.review-filters span {
  font-weight: bold;
  color: #333;
}
.review-item-card {
  margin-bottom: 20px;
}
.review-header-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.review-header-info .username {
  margin-left: 10px;
  font-weight: bold;
  color: #333;
}
.review-header-info .el-rate {
  margin-left: 10px;
}
.review-content {
  font-size: 15px;
  line-height: 1.6;
  color: #303133;
  margin-bottom: 10px;
}
.comment-image-wrapper {
  margin-top: 10px;
}
.teacher-reply {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9eb; /* Element Plus success light color */
  border-left: 4px solid #67c23a; /* Element Plus success color */
  font-size: 14px;
  color: #606266;
}
.review-actions {
  text-align: right;
}
.pagination-container {
  margin-top: 30px;
  text-align: center;
}
</style>